﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UTSDAL.LINQSQL.Model;

namespace UTSDAL.LINQSQL.DAO
{
    public class SemesterDAO:GenericDAO<Semester,Guid>
    {
        /*
         * Retrieves current semester as per the System Date
         */
        public Semester getCurrentSemester()
        {
            // look for system date between start date and end date of semester
            var currentSemesterVar = from semester in base.Context.Semesters
                                     where (semester.StartDate <= System.DateTime.Now && semester.EndDate >= System.DateTime.Now)
                                     select semester;

            
            Semester currentSemester = currentSemesterVar.FirstOrDefault<Semester>();

            // if no semester is found to lies within System date, then look for next semester
            if (currentSemester == null)
            {
                currentSemester = getNextSemester();

                // if next semester is not found, then use the first semester found in database
                if (currentSemester == null)
                {
                    currentSemester = base.Context.Semesters.FirstOrDefault<Semester>();
                }
            }

            return currentSemester;
        }
        /// <summary>
        /// gets the next semester according to the current date
        /// </summary>
        /// <returns>Semester, a semester object representing the next semester</returns>
        public Semester getNextSemester()
        {
            var nextSemesterVar = from semester in base.Context.Semesters
                                     where (semester.StartDate >= System.DateTime.Now )
                                     select semester;


            Semester nextSemester = nextSemesterVar.FirstOrDefault<Semester>();

            return nextSemester;
        }

        /// <summary>
        /// verifies that the generation process has occured or not for a particualr
        /// semester
        /// </summary>
        /// <param name="semester">semester for which timetables have been generated</param>
        /// <returns>true, if the generation process has already occured</returns>
        public Boolean areSemesterTimetablesGenerated(Semester semester)
        {
            var timetableEventsVar = from e in base.Context.TimetableEvents
                                     where e.Semester.Equals(semester)
                                     select e;

            return (timetableEventsVar.Count<TimetableEvent>() > 0);
        }

    }
}
